import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { SysUser } from '@/api/system/sysUser/sysUser.d'
import type { Result } from '@/tools/request'
import type { SysMenu } from '@/api/system/sysMenu/sysMenu.d'
import type { SysPermission } from '@/api/system/sysPermission/sysPermission.d'

export const useGlobalStore = defineStore('global', () => {
  const theme = ref(false)

  const sysUser = ref()
  const token = ref('')
  const cache = ref()
  const cacheMap = ref({})
  const permissions = ref<Permissions[]>()
  const menus = ref<SysMenu[]>()

  function changeTheme() {
    theme.value = !theme.value
  }

  function setSysUser(sysUserVal: SysUser, tokenVal: string, authority: string) {
    const authorityObj = JSON.parse(authority) as any

    menus.value = authorityObj.menus
    permissions.value = authorityObj.permissions
    localStorage.setItem('token', tokenVal)
    sysUser.value = sysUserVal
    token.value = tokenVal
  }

  function setCache(cacheVal: any) {
    const data = {} as any
    Object.keys(cacheVal).forEach(val => {
      const key = val.replace('system:', '')
      const value = JSON.parse(cacheVal[val])
      data[key] = value
    })
    cache.value = data

    const saveToCacheMap = (value: any, source: any) => {
      //第一层
      //@ts-ignore
      cacheMap.value[value] = {}
      const list = source[value]
      const fieldNameKey = value

      list.forEach((ele: any) => {
        //@ts-ignore
        cacheMap.value[fieldNameKey][ele.value] = ele['key']
      })
    }
    Object.keys(cache.value.sysDatabaseCache).forEach(value => saveToCacheMap(value, cache.value.sysDatabaseCache))
    Object.keys(cache.value.sysCache).forEach(value => saveToCacheMap(value, cache.value.sysCache))
    console.log(cacheMap.value)

  }

  return { theme, changeTheme, sysUser, token, setSysUser, cache, setCache, permissions, menus, cacheMap }
}, {
  persist: {
    key: 'global',
    storage: localStorage
  }
})
